package com.sjr.easy.chat.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sjr.easy.chat.model.User;
import com.sjr.easy.chat.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.sjr.easy.chat.repo.UserRepo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepo userRepo;

    @Override
    public List<User> getAllUser() {
        return userRepo.list();
    }

    @Override
    public User selectByPhone(String phone) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);
        return userRepo.getOne(userLambdaQueryWrapper);
    }

    @Override
    public List<User> selectByIdList(List<Long> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return new ArrayList<>();
        }
        return userRepo.listByIds(idList);
    }

    @Override
    public User selectById(Long id) {
        log.info("id:{}", id);
        if (id == null) {
            return null;
        }
        return userRepo.getById(id);
    }

    @Override
    public User selectByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            return null;
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getCode, code);
        return userRepo.getOne(queryWrapper);
    }

    @Override
    public void addUser(User user) {
        log.info("user:{}", JSON.toJSONString(user));
        userRepo.save(user);
    }

    @Override
    public void updateUserHeadPortrait(User user) {
        log.info("user:{}", JSON.toJSONString(user));
        userRepo.updateById(user);
    }

    @Override
    public void changeUserNickName(Long userId, String newNickName) {
        log.info("userId:{}, newNickName:{}", userId, newNickName);
        User entity = new User();
        entity.setId(userId);
        entity.setNickname(newNickName);
        userRepo.updateById(entity);
    }
}
